import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { BottomNavigation } from "@/components/ui/bottom-navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  MapPin,
  ChevronRight,
  ChevronDown,
  Globe,
  Expand,
  Minimize,
  Share,
} from "lucide-react";

const locationGroups = [
  {
    id: 1,
    country: "中国",
    countryFlag: "🇨🇳",
    city: "北京",
    dateRange: "2024年1月13日 - 2024年1月15日",
    coverPhoto:
      "https://images.pexels.com/photos/9373300/pexels-photo-9373300.jpeg",
    locations: [
      {
        name: "��宫博物院",
        photos: 25,
        date: "2024-01-15",
        thumbnail:
          "https://images.pexels.com/photos/9373300/pexels-photo-9373300.jpeg",
      },
      {
        name: "天安门广���",
        photos: 18,
        date: "2024-01-14",
        thumbnail:
          "https://images.pexels.com/photos/5504722/pexels-photo-5504722.jpeg",
      },
      {
        name: "颐和园",
        photos: 32,
        date: "2024-01-13",
        thumbnail:
          "https://images.pexels.com/photos/4241550/pexels-photo-4241550.jpeg",
      },
    ],
    totalPhotos: 75,
  },
  {
    id: 2,
    country: "中国",
    countryFlag: "🇨🇳",
    city: "上海",
    dateRange: "2024年1月8日 - 2024年1月10日",
    coverPhoto:
      "https://images.pexels.com/photos/2614816/pexels-photo-2614816.jpeg",
    locations: [
      {
        name: "外滩",
        photos: 28,
        date: "2024-01-10",
        thumbnail:
          "https://images.pexels.com/photos/2614816/pexels-photo-2614816.jpeg",
      },
      {
        name: "迪士尼乐园",
        photos: 45,
        date: "2024-01-09",
        thumbnail:
          "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
      },
      {
        name: "城隍庙",
        photos: 16,
        date: "2024-01-08",
        thumbnail:
          "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
      },
    ],
    totalPhotos: 89,
  },
  {
    id: 3,
    country: "中国",
    countryFlag: "🇨🇳",
    city: "杭州",
    dateRange: "2024年1月3日 - 2024年1月5日",
    coverPhoto:
      "https://images.pexels.com/photos/30629862/pexels-photo-30629862.jpeg",
    locations: [
      {
        name: "西湖",
        photos: 38,
        date: "2024-01-05",
        thumbnail:
          "https://images.pexels.com/photos/30629862/pexels-photo-30629862.jpeg",
      },
      {
        name: "灵隐寺",
        photos: 22,
        date: "2024-01-04",
        thumbnail:
          "https://images.pexels.com/photos/5504722/pexels-photo-5504722.jpeg",
      },
      {
        name: "千岛湖",
        photos: 19,
        date: "2024-01-03",
        thumbnail:
          "https://images.pexels.com/photos/3222196/pexels-photo-3222196.jpeg",
      },
    ],
    totalPhotos: 79,
  },
  {
    id: 4,
    country: "日本",
    countryFlag: "🇯🇵",
    city: "东京",
    dateRange: "2023年12月20日 - 2023年12月25日",
    coverPhoto:
      "https://images.pexels.com/photos/5220043/pexels-photo-5220043.jpeg",
    locations: [
      {
        name: "浅草寺",
        photos: 31,
        date: "2023-12-25",
        thumbnail:
          "https://images.pexels.com/photos/5220043/pexels-photo-5220043.jpeg",
      },
      {
        name: "东京塔",
        photos: 24,
        date: "2023-12-23",
        thumbnail:
          "https://images.pexels.com/photos/7993600/pexels-photo-7993600.jpeg",
      },
      {
        name: "新宿",
        photos: 18,
        date: "2023-12-20",
        thumbnail:
          "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
      },
    ],
    totalPhotos: 73,
  },
];

export default function LocationAxis() {
  const navigate = useNavigate();
  const [expandedGroups, setExpandedGroups] = useState<Set<number>>(
    new Set([1]),
  );
  const [expandedLocations, setExpandedLocations] = useState<Set<string>>(
    new Set(),
  );
  const [allExpanded, setAllExpanded] = useState(false);

  const publishToSocialMedia = (type: "region" | "location", data: any) => {
    // Store the generated content in localStorage for the social media page
    const socialMediaPost = {
      id: Date.now().toString(),
      type: type,
      source: "location",
      title:
        type === "region"
          ? `${data.city}${data.country}之旅`
          : `${data.name}的美好时光`,
      generatedAt: new Date().toISOString(),
      data: data,
    };

    localStorage.setItem("latestSocialPost", JSON.stringify(socialMediaPost));
    navigate("/social");
  };

  const toggleGroup = (groupId: number) => {
    setExpandedGroups((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(groupId)) {
        newSet.delete(groupId);
      } else {
        newSet.add(groupId);
      }
      return newSet;
    });
  };

  const toggleLocation = (groupId: number, locationName: string) => {
    const locationKey = `${groupId}-${locationName}`;
    setExpandedLocations((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(locationKey)) {
        newSet.delete(locationKey);
      } else {
        newSet.add(locationKey);
      }
      return newSet;
    });
  };

  const toggleAllGroups = () => {
    if (allExpanded) {
      setExpandedGroups(new Set());
      setAllExpanded(false);
    } else {
      setExpandedGroups(new Set(locationGroups.map((group) => group.id)));
      setAllExpanded(true);
    }
  };

  // Generate mock photos for each location
  const generateLocationPhotos = (count: number, baseThumbnail: string) => {
    const photoUrls = [
      "https://images.pexels.com/photos/9373300/pexels-photo-9373300.jpeg",
      "https://images.pexels.com/photos/5504722/pexels-photo-5504722.jpeg",
      "https://images.pexels.com/photos/4241550/pexels-photo-4241550.jpeg",
      "https://images.pexels.com/photos/2614816/pexels-photo-2614816.jpeg",
      "https://images.pexels.com/photos/30629862/pexels-photo-30629862.jpeg",
      "https://images.pexels.com/photos/5220043/pexels-photo-5220043.jpeg",
      "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
      "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
      "https://images.pexels.com/photos/3222196/pexels-photo-3222196.jpeg",
      "https://images.pexels.com/photos/7993600/pexels-photo-7993600.jpeg",
    ];

    return Array.from({ length: count }, (_, index) => ({
      id: index + 1,
      url: index === 0 ? baseThumbnail : photoUrls[index % photoUrls.length],
      alt: `Photo ${index + 1}`,
    }));
  };

  return (
    <div className="min-h-screen bg-background pb-20">
      {/* Header */}
      <header className="sticky top-0 z-40 bg-background/80 backdrop-blur-lg border-b border-border">
        <div className="flex items-center justify-between p-4">
          <div>
            <h1 className="text-2xl font-bold text-foreground">地点轴</h1>
            <p className="text-sm text-muted-foreground">按地点分组您的照片</p>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={toggleAllGroups}>
              {allExpanded ? (
                <>
                  <Minimize className="h-4 w-4 mr-2" />
                  全部收缩
                </>
              ) : (
                <>
                  <Expand className="h-4 w-4 mr-2" />
                  全部展开
                </>
              )}
            </Button>
            <Button variant="outline" size="sm">
              <Globe className="h-4 w-4 mr-2" />
              地图视图
            </Button>
          </div>
        </div>
      </header>

      {/* Content */}
      <div className="p-4 space-y-4">
        {locationGroups.map((group) => {
          const isExpanded = expandedGroups.has(group.id);

          return (
            <Card key={group.id} className="overflow-hidden">
              <CardContent className="p-0">
                {/* City Header */}
                <div
                  className="relative p-4 border-b border-border cursor-pointer overflow-hidden transition-all hover:brightness-105"
                  onClick={() => toggleGroup(group.id)}
                  style={{
                    background: `linear-gradient(to right, rgba(254, 247, 238, 0.95) 0%, rgba(254, 247, 238, 0.85) 60%, rgba(254, 247, 238, 0.7) 100%), url(${group.coverPhoto}) right center / cover no-repeat`,
                  }}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div>
                        <h3 className="font-semibold text-foreground flex items-center gap-2">
                          <span className="text-xl">{group.countryFlag}</span>
                          {group.city}, {group.country}
                        </h3>
                        <p className="text-sm text-muted-foreground">
                          {group.dateRange}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {group.totalPhotos} 张照片
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation();
                          publishToSocialMedia("region", group);
                        }}
                        className="text-xs"
                      >
                        <Share className="h-3 w-3 mr-1" />
                        发布社媒
                      </Button>
                      <Badge variant="secondary">
                        {group.locations.length} 个地点
                      </Badge>
                      {isExpanded ? (
                        <ChevronDown className="h-4 w-4 text-muted-foreground" />
                      ) : (
                        <ChevronRight className="h-4 w-4 text-muted-foreground" />
                      )}
                    </div>
                  </div>
                </div>

                {/* Locations */}
                {isExpanded && (
                  <div className="divide-y divide-border">
                    {group.locations.map((location, index) => {
                      const locationKey = `${group.id}-${location.name}`;
                      const isLocationExpanded =
                        expandedLocations.has(locationKey);
                      const locationPhotos = generateLocationPhotos(
                        location.photos,
                        location.thumbnail,
                      );

                      return (
                        <div key={index}>
                          <div className="p-4 hover:bg-muted/30 transition-colors cursor-pointer">
                            <div className="flex items-center justify-between">
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2 mb-1">
                                  <h4 className="font-medium text-foreground">
                                    {location.name}
                                  </h4>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      publishToSocialMedia("location", {
                                        ...location,
                                        region: `${group.city}, ${group.country}`,
                                      });
                                    }}
                                    className="text-xs h-6 px-2"
                                  >
                                    <Share className="h-3 w-3 mr-1" />
                                    发布
                                  </Button>
                                </div>
                                <p className="text-sm text-muted-foreground">
                                  {location.date} • {location.photos} 张照片
                                </p>
                              </div>
                              <div className="flex items-center gap-2 ml-4">
                                {/* Photo thumbnails - show up to 6 */}
                                <div className="flex gap-1">
                                  {Array.from({
                                    length: Math.min(6, location.photos),
                                  }).map((_, photoIndex) => (
                                    <div
                                      key={photoIndex}
                                      className="w-8 h-8 rounded overflow-hidden flex-shrink-0"
                                    >
                                      <img
                                        src={location.thumbnail}
                                        alt={`${location.name} photo ${photoIndex + 1}`}
                                        className="w-full h-full object-cover"
                                      />
                                    </div>
                                  ))}
                                  {location.photos > 6 && (
                                    <div className="w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0">
                                      <span className="text-xs text-muted-foreground font-medium">
                                        +{location.photos - 6}
                                      </span>
                                    </div>
                                  )}
                                </div>
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    toggleLocation(group.id, location.name);
                                  }}
                                  className="ml-2 p-1 hover:bg-background rounded transition-colors"
                                >
                                  {isLocationExpanded ? (
                                    <ChevronDown className="h-4 w-4 text-muted-foreground" />
                                  ) : (
                                    <ChevronRight className="h-4 w-4 text-muted-foreground" />
                                  )}
                                </button>
                              </div>
                            </div>
                          </div>

                          {/* Photo Grid */}
                          {isLocationExpanded && (
                            <div className="px-4 pb-4">
                              <div className="bg-muted/20 rounded-lg p-3">
                                <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-2">
                                  {locationPhotos.map((photo) => (
                                    <div
                                      key={photo.id}
                                      className="aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer hover:scale-105 transition-transform"
                                    >
                                      <img
                                        src={photo.url}
                                        alt={photo.alt}
                                        className="w-full h-full object-cover"
                                      />
                                    </div>
                                  ))}
                                </div>
                              </div>
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}
              </CardContent>
            </Card>
          );
        })}

        {/* Add Location Hint */}
        <Card className="border-dashed border-2 border-muted-foreground/20">
          <CardContent className="p-8 text-center">
            <MapPin className="h-8 w-8 text-muted-foreground mx-auto mb-3" />
            <h3 className="font-medium text-foreground mb-2">自动识别新地点</h3>
            <p className="text-sm text-muted-foreground mb-4">
              上传带有位置信息的照片，系统会自动为您创建地点分组
            </p>
            <Button variant="outline">了解更多</Button>
          </CardContent>
        </Card>
      </div>

      <BottomNavigation />
    </div>
  );
}
